package com.yhh.college_information_platform.controller;

import com.yhh.college_information_platform.annotation.RequireAuth;
import com.yhh.college_information_platform.common.PageResult;
import com.yhh.college_information_platform.common.Result;
import com.yhh.college_information_platform.service.DownloadRecordService;
import com.yhh.college_information_platform.vo.DownloadRecordVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 下载记录管理Controller（所有接口需要登录）
 *
 * @author yhh
 * @date 2025-10-25
 */
@Slf4j
@RestController
@RequestMapping("/download")
@RequireAuth  // 整个Controller都需要登录
public class DownloadRecordController {

    @Autowired
    private DownloadRecordService downloadRecordService;

    /**
     * 添加下载记录
     */
    @PostMapping("/{resourceId}")
    public Result<Void> addDownloadRecord(@PathVariable Long resourceId, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        String ip = getClientIp(request);
        downloadRecordService.addDownloadRecord(userId, resourceId, ip);
        return Result.success();
    }

    /**
     * 获取用户的下载记录
     */
    @GetMapping("/my")
    public Result<PageResult<DownloadRecordVO>> getUserDownloadRecords(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        PageResult<DownloadRecordVO> pageResult = downloadRecordService.getUserDownloadRecords(userId, current, size);
        return Result.success(pageResult);
    }

    /**
     * 获取客户端IP地址
     */
    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}

